package com.lunker.moneyrecord;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Environment;
import android.widget.Toast;

public class ExportCSVTask extends AsyncTask<Void, Void, Boolean>{
	
	private Context context;
	private BetterProgressDialog progressDlg = null;
	private static final String CSV_FILE_NAME = "MoneyRecord.csv";

	public ExportCSVTask (Context c) {
		context = c;
	}
	
	@Override
	protected void onPreExecute() {
		progressDlg = new BetterProgressDialog(context);
		progressDlg.show();
	}
	
	@Override
	protected Boolean doInBackground(Void... params) {
		
		if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {			
			return false;
		}
		
		File fout = new File(Environment.getExternalStorageDirectory(), CSV_FILE_NAME);
		MyDatabaseOpenHelper helper = new MyDatabaseOpenHelper(context);
		SQLiteDatabase mydb = helper.getReadableDatabase();
		Cursor cr = mydb.query("money_record", null, null, null, null, null, null);
		FileWriter fw = null;
		
		try {			
			fout.createNewFile();
			fw = new FileWriter(fout);
			
			//Write column names.
			String colNames[] = cr.getColumnNames();
			StringBuilder sb = new StringBuilder();
			
			for (String col : colNames) {
				sb.append(",").append(col);
			}
			fw.write(sb.substring(1));
			fw.write("\n");
			
			//Write data
			while(cr.moveToNext()) {
				sb = new StringBuilder();
				
				for (int i = 0; i < cr.getColumnCount(); i++) {
					sb.append(",").append(cr.getString(i));
				}
				fw.write(sb.substring(1));
				fw.write("\n");
			}
			
			return true;
		} catch (IOException ioe) {
			ioe.printStackTrace();
			return false;
		} finally {
			cr.close();
			mydb.close();
			
			try {
				if (fw != null) {
					fw.close();
				}
			} catch (IOException ioe) {
				ioe.printStackTrace();
			}
		}
	}

	@Override
	protected void onPostExecute(Boolean result) {
		progressDlg.dismiss();
		
		if (result) {
			Toast.makeText(context, context.getString(R.string.export_csv_successfully), 
					Toast.LENGTH_SHORT).show();
		} else {
			Toast.makeText(context, context.getString(R.string.fail_to_export_csv), 
					Toast.LENGTH_SHORT).show();
		}
	}
}
